package de.hijacksoft.isle;

import static de.hijacksoft.isle.classes.Variables.*;

import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import de.hijacksoft.isle.adapters.DBAdapter;
import de.hijacksoft.isle.classes.Item;
import de.hijacksoft.isle.adapters.MainListAdapter;

/**
 * This activity displays the history of all bought items.
 * It is very similar to the ItemSelectActivity. This is why there is not much comments in this class
 * @author HiJack Soft
 */
public class HistoryActivity extends Activity {

    private static final String TAG = "HistoryActivity";
    private ArrayList<Item> infos;
    private MainListAdapter myAdapter;
    private DBAdapter adapter;
    private boolean itemClickable = false;
    // Views
    private Button add, clear, history;
    private ListView list;
    private EditText searchBar;
    private ArrayList<Item> itemsToAdd = new ArrayList<Item>();
    // Mode
    public static final int MODE_MAIN = 0;      // will add items to the main list
    public static final int MODE_RECIPE = 1;    // will add items to the recipe list
    public static final String KEY_MODE = "mode";
    private int mode;
    private int prevSortmode; // the previous sort mode (e.g. the sort mode of the ItemSelectActivity)

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.itemselect);

        // get the mode from the extras
        mode = getIntent().getExtras().getInt(KEY_MODE);

        // set the previous sort mode to preserve it until onDestroy
        prevSortmode = Item.getSortMode();
        Item.setSortMode(Item.SORT_HISTORY);

        initDB();
        createUI();
        initList();

    }

    /**
     * check if the clear button should be disabled
     */
    public void checkClearButton() {
        if (myAdapter.getCount() > 0) {
            clear.setEnabled(true);
        } else {
            clear.setEnabled(false);
        }
    }

    public void initDB() {
        adapter = new DBAdapter(this);
        adapter.open();
    }

    public void createUI() {

        add = (Button) findViewById(R.id.itemselect_btn_add);
        clear = (Button) findViewById(R.id.itemselect_btn_clear);
        list = (ListView) findViewById(R.id.itemselect_list_selectitem);
        history = (Button) findViewById(R.id.itemselect_btn_history);

        history.setVisibility(View.GONE);
        clear.setVisibility(View.VISIBLE);

        add.setVisibility(View.GONE);

        LinearLayout listHeader = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.searchbarheader, null);

        searchBar = (EditText) listHeader.findViewById(R.id.searchbarheader_edittext_search);
        
        list.addHeaderView(listHeader);
        
        searchBar.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {

                Collections.sort(infos);

                if (!searchBar.getText().equals("")) {
                    int count = 0;
                    for (int i = 0; i < infos.size(); i++) {
                        if (infos.get(i).name.toLowerCase().contains(searchBar.getText().toString().toLowerCase())) {
                            Item item = infos.get(i);
                            infos.remove(item);
                            infos.add(count, item);
                            count++;
                        }
                    }
                }
                myAdapter.notifyDataSetChanged();
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }
        });

        add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                startActivityForResult(new Intent(HistoryActivity.this, ItemActivity.class),
                        ITEM_RETURNED);
            }
        });

        clear.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                clearListQuestion();
            }
        });

        list.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                if (itemClickable) {
                    ItemEditQuestion(arg2);
                }
                return true;
            }
        });

        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                if (itemClickable) {
                    itemsToAdd.add(infos.get(arg2));
                    String text = "";
                    switch (mode) {
                        case MODE_MAIN:
                            text = getString(R.string.itemaddedtolist).replace("$n", infos.get(arg2).name);
                            break;
                        case MODE_RECIPE:
                            text = getString(R.string.itemaddedtorecipe).replace("$n", infos.get(arg2).name);
                            break;
                    }
                    Toast.makeText(HistoryActivity.this, text, Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void ItemEditQuestion(final int position) {
        AlertDialog.Builder dB = new AlertDialog.Builder(this);
        dB.setTitle(infos.get(position).name);
        dB.setMessage(getString(R.string.editquestion));
        dB.setPositiveButton(getString(R.string.edit), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                Intent data = new Intent(HistoryActivity.this, ItemActivity.class);
                data.putExtra("id", infos.get(position).id);
                startActivityForResult(data, ITEM_RETURNED);
            }
        });
        dB.setNegativeButton(getString(R.string.delete), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                adapter.removeFromHistory(infos.get(position));
                infos.remove(position);
                myAdapter.notifyDataSetChanged();
                checkClearButton();
            }
        });
        AlertDialog d = dB.create();
        d.show();
    }

    private void initList() {
        if (infos == null) {
            infos = new ArrayList<Item>();
        }
        myAdapter = new MainListAdapter(this, R.layout.item, infos, adapter);
        list.setAdapter(myAdapter);
        LoadItemsTask lt = new LoadItemsTask();
        lt.execute(0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ITEM_RETURNED:
                    initList();
                    break;
            }
        }
        myAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        startActivity(new Intent(this, Preferences.class));
        return false;
    }

    public void clearListQuestion() {
        AlertDialog.Builder dB = new AlertDialog.Builder(this);
        dB.setTitle(R.string.clear);
        dB.setMessage(R.string.clearlist);
        dB.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                adapter.clearHistory();
                infos.clear();
                myAdapter.notifyDataSetChanged();
                checkClearButton();
            }
        });
        dB.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
            }
        });
        AlertDialog d = dB.create();
        d.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkClearButton();
    }

    private class LoadItemsTask extends AsyncTask<Integer, Integer, Integer> {

        @Override
        protected void onPreExecute() {
            itemClickable = false;
            infos.clear();
            myAdapter.setMode(MainListAdapter.PRICE, false);
            myAdapter.setMode(MainListAdapter.ICONS, false);
            myAdapter.setMode(MainListAdapter.CHECKBOX, false);
            myAdapter.setMode(MainListAdapter.AMOUNT, false);
            myAdapter.setMode(MainListAdapter.LASTBOUGHT, true);
            Item loadItem = new Item();
            loadItem.name = getString(R.string.loading);
            loadItem.image = null;
            loadItem.price = 0;
            infos.add(loadItem);
            myAdapter.notifyDataSetChanged();
        }

        @Override
        protected Integer doInBackground(Integer... arg) {
            infos = adapter.getHistory();
            return null;
        }

        @Override
        protected void onPostExecute(Integer result) {
            itemClickable = true;
            myAdapter = new MainListAdapter(HistoryActivity.this, R.layout.item, infos, adapter);
            list.setAdapter(myAdapter);
            myAdapter.setMode(MainListAdapter.PRICE, false);
            myAdapter.setMode(MainListAdapter.ICONS, true);
            myAdapter.setMode(MainListAdapter.CHECKBOX, false);
            myAdapter.setMode(MainListAdapter.AMOUNT, true);
            myAdapter.setMode(MainListAdapter.LASTBOUGHT, true);
            myAdapter.notifyDataSetChanged();
            checkClearButton();

            searchBar.setVisibility(View.VISIBLE);
            
            list.setSelectionFromTop(1, searchBar.getHeight());

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {

            case KeyEvent.KEYCODE_BACK:
                if (itemsToAdd.size() == 0) {
                    HistoryActivity.this.setResult(RESULT_CANCELED, null); // Cancelled
                } else {
                    Intent data = new Intent();
                    for (int i = 0; i < itemsToAdd.size(); i++) {
                        data.putExtra("id_" + i, itemsToAdd.get(i).id);
                    }
                    HistoryActivity.this.setResult(RESULT_OK, data);       // Ok
                }
                break;
            case KeyEvent.KEYCODE_SEARCH:
                list.setSelectionFromTop(0, 0);
                new Handler(Looper.getMainLooper()).post(new Thread(){
                    @Override
                    public void run(){
                        do{
                            searchBar.requestFocus();
                            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(searchBar,InputMethodManager.SHOW_FORCED); 
                        }while(!searchBar.hasFocus());
                    }
                });
                break;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Item.setSortMode(prevSortmode);
        try{
            adapter.close();
        }
        catch(Exception e){
            Log.d(TAG, "Error closing the database adapter: " + e.toString());
        }
    }
}
